<?php
/* QQ:34734852
 * 业务联系：小鱼
 */
class TempLate{
	public static $ini = array(500);
	private static $VariableGroup = array();
	private static  $BanNo = 0;
	
	public function Start( $Arr = array() ) {
		    TempLate::$ini = $Arr;
			TempLate::$VariableGroup[ 'Config' ] = $Arr;
	}
	public function Theme( $Dir = 'Default' ) {
		    TempLate::$ini['TempLate'] = $Dir;
			unset( $Dir );
	}
	
	public function get() {
		    return TempLate::$ini['TempLate'];
	}
	
	public function CacheDir( $key = '' ) {
		if ( empty( $key ) ) {
			return TempLate::$ini['CacheDir'];
		} else {
			TempLate::$ini['CacheDir'] = $key;
		}
	}
	
	public function assign( $Name = 'Config', $Val = '' ) {
		   TempLate::$VariableGroup[ $Name ] = $Val;
		   unset( $Name, $Val );
		   return $this;
	}
	
	public function display( $FileName = '', $Stop = true, $Out = false ) {
		  is_dir( ROOT . APP . '/' . TempLate::$ini['CacheDir'] ) or mkdir(ROOT . APP . '/' . TempLate::$ini['CacheDir']);
		  $TemplateFile = empty( $FileName ) ?  ROOT . APP . '/Template/' . TempLate::$ini['TempLate'] . '/' .  ACTI .  TempLate::$ini['Extension'] :  ROOT . APP . '/Template/' . TempLate::$ini['TempLate'] . '/' .  $FileName .  TempLate::$ini['Extension'];
		  $CacheFile    = empty( $FileName ) ?  ROOT . APP . '/' . TempLate::$ini['CacheDir'] . '/' . ACTI . '.' . md5(m) .  '.tpl.php' :  ROOT . APP . '/' . TempLate::$ini['CacheDir'] . '/' . $FileName . '.' .  md5($FileName) .  '.tpl.php';
		  $CacheTime = file_exists( $CacheFile ) ?  round((time() - filemtime( $CacheFile )) / 60, 2) : TempLate::$ini['Cache'];
		  if ( !file_exists( $CacheFile ) || $CacheTime >= TempLate::$ini['Cache'] ) {
			  if ( !file_exists( $TemplateFile ) ) {
				  $this -> TplError( '模板' . (empty( $FileName ) ? ACTI : $FileName) . TempLate::$ini['Extension'] . '不存在，无法解析文档' );
				  return false;
			  }
			  $TemplateCode = file_get_contents( $TemplateFile );
			  $PHPCodeData = $this-> CodeProcessing( $TemplateCode );
			  file_put_contents( $CacheFile, trim($PHPCodeData) );
			  $Tidy = $TemplateCode = $PHPCodeData = $TemplateFile = $CacheTime = null;
		  }
		  
		  extract( TempLate::$VariableGroup,  EXTR_SKIP );
		  ob_start();
		    include_once $CacheFile;
		    $ConTents = ob_get_contents();
		  ob_end_clean();
		  unset( $CacheFile, $CacheTime, $FileName, $TemplateCode, $TemplateFile, $Tidy, $PHPCodeData );
		  if ( !$Out ) {
			  echo $ConTents;
			  if ( !$Stop ) {
				die;  
			  }
		  } else {
			  return $ConTent;
		  }
	}
	
	private function CodeProcessing( $Code = '' ) {
		  $Code = preg_replace('/\s+(src|href)\s?=\s?[\'"]?(http\:\/{2}|https\:\/{2}|\/|\#)([^\'"\s]*)[\'"]/is', ' cache$1="$2$3"', $Code);
		  $Code = preg_replace('/\s?tpl\_(\w+)\s?=\s?[\'"]?([^\'"]*)[\'"]?/is', ' $1 = "/' . APP . '/Template/' . TempLate::$ini['TempLate'] . '/$2"', $Code);
		  $Code = preg_replace('/\s+(src|href)\s?=\s?[\'"]?([^\'"\s]*)[\'"]/is', ' $1="/'. App . '/Template/' . TempLate::$ini['TempLate']. '/$2"', $Code);
		  $Code = preg_replace('/\:\s?url\s?\(\s?[\'"]?([^\'"\)]*)[\'"]?\s?\)/is', ':url(/'. App . '/Template/' . TempLate::$ini['TempLate']. '/$1)', $Code);
		  $Code = preg_replace('/\s?data\-dir\s?=\s?[\'"]?([^\'"]*)[\'"]?/is', ' data-dir = "/' . APP . '/Template/' . TempLate::$ini['TempLate'] . '/$1"', $Code);
		  $Code = preg_replace('/\s+cache(src|href)\s?=\s?/is', ' $1=', $Code);
		  $Repl = array(
		         '\s?(?:Tpl::|include\s+)(\w+)'   => '<?php \$this -> display( \'$1\' ) ?>',
		         '\s?\$\s?(\w+)\.(\d+)' => '<?php echo \$$1[ $2 ] ?>',
		         '\s?\$\s?(\w+)\.(\w+)' => '<?php echo \$$1[\'$2\'] ?>',
				 '\s?\$\s?(\w+)'        => '<?php echo \$$1 ?>',
				 '\s?loop\s+(\w+)\s?=\s?(\w+)' => '<?php if ( is_array( \$$1 ) && sizeof( $$1 ) ) { $Count = 0; foreach( \$$1 as \$Key => \$$2 ) { $Count++; ?>',
				 '\s?\/\s?loop' => '<?php }}unset( $Count, $Key );?>',

				 '\s?foreach\s+(\w+)\s?=\s?(\w+)\s+key\s?=\s?(\w+)\s?' => '<?php if ( is_array( \$$1 ) && sizeof( $$1 ) ) { $Size = 0; foreach( \$$1 as \$$3 => \$$2 ) { $Size++; ?>',
				 '\s?\/\s?foreach' => '<?php }} ?>',
				 
				 '\s?if\s+\#\s?([^\#]*)' => '<?php if ( $1 ) { ?>',
				 '\s?else\s?if\s+\#\s?([^\#]*)' => '<?php } elseif ( $1 ) { ?>',
				 '\s?else' => '<?php } else { ?>',
				 '\s?\/\s?if'   => '<?php } ?>',
				 '\s?php'       => '<?php ',
				 '\s?\/\s?php'  => ' ?>',
				 '\s?function\s+\#\s?([^\#]*)\s?\#' => '<?php $1 ?>',
				 '\s?js\s?=\s?[\'"](\w+)\(([^\)]*)\)[\'"]\s?' => '<div id="js#T#"></div><script>$1($2, \$(\'#js#T#\'))</script>',
				 '\s?\:\s?(\w+)\s?\(([^\)]*)\)\s?' => '<?php $this -> $1($2) ?>',
				 '\s?print\s?\(\s?(\w+)\s?\)\s?' => '<?php print_r( \$$1 ); ?>',
				 '\s?print\s?\(\s?(\w+),\s?(\w+)\)\s?' => '<?php var_dump( \$$1 ); ?>',
				 '\s?sql\s?=\s?([\'"]+)([^\'"]*)([\'"])\s+t\s?=\s?(\d+)\s+k\s?=\s?(\w+)\s?' => '<?php \$$5 = $Mdata -> execute( $1$2$3, $4); ?>'
		  );
		  foreach( $Repl as $Regular => $Replace ) {
		   self::$BanNo+=1;
		   $Preg =  '/' . TempLate::$ini['StartTag'] .  $Regular  .  '[^' . TempLate::$ini['EndTag'] . ']*' . TempLate::$ini['EndTag'] . '/is';
		   $Code = preg_replace( $Preg, $Replace, $Code );
		   $Code = str_replace( '#T#', self::$BanNo, $Code );
		  }
		  
		  $Code = preg_replace('/\s?\$\s?(\w+)\.(\d+)\s?/is', '\$$1[ $2 ]', $Code);
		  $Code = preg_replace('/\s?\$\s?(\w+)\.(\w+)\s?/is', '\$$1[\'$2\']', $Code);
		  $Code = preg_replace('/out\./is', '', $Code);
		  $Code = preg_replace('/\s+$/is', '', $Code);
		  
		  unset( $Repl, $Regular, $Preg, $Replace );
		  return '<?php if ( !class_exists(\'TempLate\') ) { die; } ?>' . $Code;
	}
	
	private function rurl( $h = 'home', $m = 'index', $c = 'index', $f = '', $out = false ) {
		!empty( $h ) or $h = 'home';
		!empty( $m ) or $m = 'index';
		!empty( $c ) or $c = 'index';
		$f                 = str_replace('?', rand(), $f);
		if ( TempLate::$ini['webstatic'] ) {
			$Url = '/' . $h . '/' . $m . '/' . $c;
		} else {
			$Url = '/?h=' . $h . '&m=' . $m . '&c=' . $c;
		}
		if ( !empty( $f ) ) {
			if ( TempLate::$ini['webstatic'] ) {
				$s = explode( '&', $f );
				if ( is_array( $s ) ) {
				  foreach( $s as $p ) {
					$g = explode('=', $p );
					$Url .= '/' . $g[0] . '/' . $g[1];
				  }
				}
			} else {
				$Url .= '&' . $f;
			}
		}
		
		unset( $h, $m, $c, $f, $s, $g );
		if ( !$out ) {
		   echo $Url;
		   unset( $out, $Url );	
		} else {
		  unset( $out );
		  return $Url;
		}
	}
	
	
	public function __destruct() {
		   TempLate::$ini = TempLate::$VariableGroup = array();
	}
	
	private function TplError( $Msg = '', $Exit = true ) {
		  include_once LIB . 'Template/Error_Write.tpl';
		  unset( $Msg );
		  if( !$Exit ) {
			 unset( $Exit, $Msg );
			 die; 
		  }
		  unset( $Exit, $Msg );
	}
	
	
}